#include<memory>
#include"Reactor.hpp"
#include"Epoller.hpp"
#include"Socket.hpp"
#include"Connection.hpp"
#include"Common.hpp"
#include"InetAddr.hpp"
#include"Channel.hpp"
using namespace SocketModule;

class Listener:public Connection
{
    public:
    Listener(int port=defaultfd)
    :_port(port),_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildTcpSocketMethod(_port);
        SetEvent(EPOLLIN|EPOLLET);
        SetNonBlock(_listensock->Fd());
    }
    ~Listener(){}
    void Recver()override
    {
        InetAddr client;
        while(true)
        {
            int sockfd=_listensock->Accept(&client);
            if(sockfd==ACCEPT_ERR)
                break;
            else if(sockfd==ACCEPT_CONTINUE)
                continue;
            else if(sockfd==ACCEPT_DONE)
                break;
            else
            {
                //构建一个Channel
                std::shared_ptr<Connection> conn=std::make_unique<Channel>(sockfd,client);

                //设置Channel的事件
                conn->SetEvent(EPOLLIN|EPOLLET);
                if(_handler !=nullptr)
                {
                    //将_listensock的_handler函数指针赋值给Channel,让Channel处理inbuffer返回计算结果Json格式的response报文

                    conn->RegisterHandler(_handler);
                }
                //让所属的Reactor调用方法来田间新的Channel
                GetOwner()->AddConnection(conn);
            }
        }
        // LOG(LogLevel::DEBUG)<<"进入Listener的Recver";
    }
    void Sender(){}
    void Excepter(){}
    int GetSockFd()
    {
        return _listensock->Fd();
    }
    private:
    int _port;
    std::unique_ptr<Socket>_listensock;
};